<template>
  <div class="app-container">
    <div class="filter-container">
      <el-select v-if="false" v-model="listQuery.lineId" :placeholder="$t('equipment.lineNumber')" class="filter-item" style="width: 200px" @change="handleFilter">
        <el-option v-for="item in lineOptions" :key="item.lineId" :label="item.lineName" :value="item.lineId" />
      </el-select>
      <el-checkbox v-model="showReviewer" class="filter-item" style="margin-left:15px;">
        {{ $t('equipment.showAllProcess') }}
      </el-checkbox>
      <el-button v-waves class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-search" @click="handleFilter">
        {{ $t('common.search') }}
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-edit" @click="handleCreate">
        {{ $t('common.creatNew') }}
      </el-button>
    </div>
    <!-- 主界面数据 -->
    <el-table
      ref="dragTable"
      v-loading="listLoading"
      row-key="stationNumber"
      :data="list"
      :header-row-style="{color: 'black'}"
      :header-cell-style="{background: 'lightBlue'}"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column align="center" width="80">
        <template slot-scope="{}">
          <svg-icon class="drag-handler" icon-class="drag" />
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.stationNumber')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.stationNumber }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.stationCode')" width="150" align="center">
        <template slot-scope="{row}">
          <span>{{ row.stationCode }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.stationName')" width="250px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.stationName }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.ipAddr')" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.ipAddr }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.cycleTimeSd')" width="100px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.cycleTimeSd }}</span>
        </template>
      </el-table-column>
      <el-table-column :label="$t('equipment.process1')" align="center">
        <el-table-column :label="$t('equipment.processNumber')" width="140px" align="center">
          <template slot-scope="{row}">
            <span class="link-type" @click="handleCheckProcess(row.lineNumber,row.processes[0].processNumber)">{{ row.processes[0].processNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('equipment.processName')" width="250px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.processes[0].processName }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column v-if="showReviewer" :label="$t('equipment.process2')" align="center">
        <el-table-column :label="$t('equipment.processNumber')" width="120px" align="center">
          <template slot-scope="{row}">
            <span class="link-type" @click="handleCheckProcess(row.lineNumber,row.processes[1].processNumber)">{{ row.processes[1].processNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('equipment.processName')" width="250px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.processes[1].processName }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column v-if="showReviewer" :label="$t('equipment.process3')" align="center">
        <el-table-column :label="$t('equipment.processNumber')" width="120px" align="center">
          <template slot-scope="{row}">
            <span class="link-type" @click="handleCheckProcess(row.lineNumber,row.processes[2].processNumber)">{{ row.processes[2].processNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('equipment.processName')" width="250px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.processes[2].processName }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column v-if="showReviewer" :label="$t('equipment.process4')" align="center">
        <el-table-column :label="$t('equipment.processNumber')" width="120px" align="center">
          <template slot-scope="{row}">
            <span class="link-type" @click="handleCheckProcess(row.lineNumber,row.processes[3].processNumber)">{{ row.processes[3].processNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('equipment.processName')" width="250px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.processes[3].processName }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column v-if="showReviewer" :label="$t('equipment.process5')" align="center">
        <el-table-column :label="$t('equipment.processNumber')" width="120px" align="center">
          <template slot-scope="{row}">
            <span class="link-type" @click="handleCheckProcess(row.lineNumber,row.processes[4].processNumber)">{{ row.processes[4].processNumber }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('equipment.processName')" width="250px" align="center">
          <template slot-scope="{row}">
            <span>{{ row.processes[4].processName }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column :label="$t('common.operation')" align="center" width="200px" class-name="small-padding fixed-width">
        <template slot-scope="{row,$index}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            {{ $t('common.edit') }}
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row,$index)">
            {{ $t('common.delete') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 新建和更新对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form ref="dataForm" :rules="rules" :model="temp" label-position="left" label-width="150px" style="width: 600px; margin-left:50px;">
        <el-form-item :label="$t('equipment.stationNumber')" required prop="stationNumber">
          <el-input v-model="temp.stationNumber" :placeholder="$t('equipment.stationNumber')" />
        </el-form-item>
        <el-form-item :label="$t('equipment.stationCode')">
          <el-input v-model="temp.stationCode" :placeholder="$t('equipment.stationCode')" />
        </el-form-item>
        <el-form-item :label="$t('equipment.stationName')" required prop="stationName">
          <el-input v-model="temp.stationName" :placeholder="$t('equipment.stationNumber')" />
        </el-form-item>
        <el-form-item :label="$t('equipment.ipAddr')">
          <el-input v-model="temp.ipAddr" :placeholder="$t('equipment.ipAddr')" />
        </el-form-item>
        <el-form-item required prop="cycleTimeSd" :label="$t('equipment.cycleTimeSd')">
          <el-input v-model="temp.cycleTimeSd" :placeholder="$t('equipment.cycleTimeSd')" />
        </el-form-item>
        <el-form-item :label="$t('equipment.processNumber')+'1'" required prop="processes[0].processNumber">
          <el-input v-model="temp.processes[0].processNumber" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.processName')+'1'" required prop="processes[0].processName">
          <el-input v-model="temp.processes[0].processName" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.processNumber')+'2'">
          <el-input v-model="temp.processes[1].processNumber" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.processName')+'2'">
          <el-input v-model="temp.processes[1].processName" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.processNumber')+'3'">
          <el-input v-model="temp.processes[2].processNumber" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.processName')+'3'">
          <el-input v-model="temp.processes[2].processName" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.processNumber')+'4'">
          <el-input v-model="temp.processes[3].processNumber" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.processName')+'4'">
          <el-input v-model="temp.processes[3].processName" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.processNumber')+'5'">
          <el-input v-model="temp.processes[4].processNumber" clearable />
        </el-form-item>
        <el-form-item :label="$t('equipment.processName')+'5'">
          <el-input v-model="temp.processes[4].processName" clearable />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          {{ $t('common.cancel') }}
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          {{ $t('common.ok') }}
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Table, TableColumn } from 'element-ui'
import Sortable from 'sortablejs'
import { getLineList, getStationList, creatStation, updateStation, deleteStation } from '@/api/equipment'
import waves from '@/directive/waves' // waves directive
import { parseTime } from '@/utils'
import i18n from '@/lang'

export default {
  name: 'StationDef',
  components: {
    ElTable: Table,
    ElTableColumn: TableColumn
  },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  data() {
    const validateCycleTime = (rule, value, callback) => {
      if (this.temp.cycleTimeSd <= 0) {
        callback(new Error(i18n.t('msg.CAN_NOT_BE_NULL')))
      } else {
        callback()
      }
    }
    return {
      editRight: true,
      tableKey: 0,
      list: [],
      newList: [],
      sortable: null,
      lineOptions: [],
      // 任务u状态
      stateOptions: [{ label: '所有', key: 0, color: 'white' },
        { label: '进行中', key: 1, color: 'green' },
        { label: '延期', key: 2, color: 'orange' },
        { label: '完成', key: 3, color: 'darkblue' },
        { label: '取消', key: 4, color: 'red' },
        { label: '暂停', key: 5, color: 'yellow' }],
      total: 0,
      listLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        state: 0,
        lineId: this.$store.getters.lineId,
        lineName: this.$store.getters.lineNumber,
        lineNumber: '',
        startTime: parseTime(Date.now(), '{y}-{m}-{d} 00:00:00'),
        endTime: '',
        sort: '+sequence'
      },
      showReviewer: false,
      showRemark: false,
      temp: {
        lineId: 1,
        stationId: 1,
        stationNumber: '',
        stationName: '',
        stationCode: '',
        cycleTimeSd: 0,
        processes: [
          { processId: 0, processNumber: '', processName: '' },
          { processId: 0, processNumber: '', processName: '' },
          { processId: 0, processNumber: '', processName: '' },
          { processId: 0, processNumber: '', processName: '' },
          { processId: 0, processNumber: '', processName: '' }]
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: i18n.t('common.edit'),
        create: i18n.t('common.creatNew')
      },
      dialogPvVisible: false,
      pvData: [],
      rules: {
        stationNumber: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        stationName: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        lineNumber: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        processNumber1: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        processName1: [{ required: true, message: i18n.t('msg.CAN_NOT_BE_NULL'), trigger: 'change' }],
        cycleTimeSd: [{ required: true, trigger: 'blur', validator: validateCycleTime }]
      },
      downloadLoading: false,
      searchLoading: {
        director: false
      },
      searchDialogStatus: '',
      searchDialogFormVisible: {
        director: false
      }
    }
  },
  // watch: {
  //   $route: {
  //     handler(val) {
  //       if (this.$route.query.lineId !== undefined) {
  //         this.listQuery.lineId = this.$route.query.lineId
  //         this.getLineList()
  //         this.getList()
  //       }
  //     }
  //   }
  // },
  created() {
    this.editRight = (this.$store.getters.roles === 'admin' || this.$store.getters.roles === 'administrator')
    this.listQuery.lineId = this.$store.getters.lineId
    this.listQuery.lineNumber = this.$store.getters.lineNumber
    // console.log(this.listQuery.lineNumber)
    this.getLineList()
    this.getList()
  },
  mounted() {
    this.setSort()
    this.$nextTick(() => {
      this.setSort()
    })
  },
  methods: {
    timestepToolTip(index) {
      return index + '%'
    },
    formatDateTime(date) {
      return date.substring(0, 10)
    },
    // 行拖拽
    setSort() {
      const el = this.$refs.dragTable.$el.querySelectorAll(
        '.el-table__body-wrapper > table > tbody'
      )[0]
      this.sortable = Sortable.create(el, {
        ghostClass: 'sortable-ghost',
        setData: function(dataTransfer) {
          dataTransfer.setData('Text', '')
        },
        onEnd: evt => {
          const targetRow = this.list.splice(evt.oldIndex, 1)[0]
          this.list.splice(evt.newIndex, 0, targetRow)
          const tempIndex = this.newList.splice(evt.oldIndex, 1)[0]
          this.newList.splice(evt.newIndex, 0, tempIndex)
          this.flag = true
          // console.log(this.list)
        }
      })
    },
    isEmptyLineId: function() {
      var ret = (this.listQuery.lineNumber === undefined || this.listQuery.lineNumber === '')
      if (ret) {
        this.$notify({
          title: this.$i18n.t('common.tip'),
          message: i18n.t('msg.NO_LINE_SELECTED'),
          type: 'success',
          duration: 2000
        })
      }
      return ret
    },
    // 获取线体清单
    getLineList() {
      this.listLoading = true
      getLineList(this.listQuery).then(response => {
        this.lineOptions = response.data.lines
        this.listLoading = false
      })
    },
    // 获取清单
    getList() {
      if (this.isEmptyLineId() === false) {
        this.listLoading = true
        getStationList(this.listQuery).then(response => {
          // console.log(response)
          this.list = response.data.stations
          this.total = response.data.total
          this.listLoading = false
          this.list.forEach(ele => {
            var len = ele.processes.length
            var i = 1
            for (i = len; i <= 5; i++) {
              ele.processes.push({ processId: 0, processNumber: '', processName: '' })
            }
          })
        })
      }
    },
    // 查看工艺参数
    handleCheckProcess(lineNumber, processNumber) {
      this.$router.push({ path: '/equipment/processResultDef', query: { lineNumber: lineNumber, processNumber: processNumber }})
    },
    // 点击搜索时获取清单
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    // 初始化创建信息
    resetTemp() {
      this.temp = {
        lineNumber: this.listQuery.lineNumber,
        lineId: this.listQuery.lineId,
        stationId: 0,
        stationNumber: '',
        stationName: '',
        stationCode: '',
        cycleTimeSd: 0,
        ipAddr: '',
        processes: [
          { processId: 0, processNumber: '', processName: '' },
          { processId: 0, processNumber: '', processName: '' },
          { processId: 0, processNumber: '', processName: '' },
          { processId: 0, processNumber: '', processName: '' },
          { processId: 0, processNumber: '', processName: '' }]
      }
    },
    // 新建一个工站
    handleCreate() {
      if (this.isEmptyLineId() === false) {
        this.resetTemp()
        this.dialogStatus = 'create'
        this.dialogFormVisible = true
        this.$nextTick(() => {
          this.$refs['dataForm'].clearValidate()
        })
      }
    },
    // 创建数据
    createData() {
      this.temp.lineNumber = this.listQuery.lineNumber
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          creatStation(this.temp).then(response => {
            this.list.unshift(response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.CREAT_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.getList()
          })
        }
      })
    },
    // 点击编辑按钮
    handleUpdate(row) {
      this.temp = Object.assign({}, row) // copy obj
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    // 更新数据到数据库
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          updateStation(this.temp).then(response => {
            const index = this.list.findIndex(v => v.stationId === this.temp.stationId)
            this.list.splice(index, 1, response.data)
            this.dialogFormVisible = false
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.UPDATE_SUCCESS'),
              type: 'success',
              duration: 2000
            })
          })
        }
      })
    },
    // 删除数据库信息
    handleDelete(row, index) {
      this.$confirm(i18n.t('msg.DELET_INFO_CONFIRM'), i18n.t('common.warn'), {
        confirmButtonText: i18n.t('common.confirm'),
        cancelButtonText: i18n.t('common.cancel'),
        type: 'warning'
      })
        .then(async() => {
          this.temp = Object.assign({}, row) // copy obj
          deleteStation(this.temp).then(() => {
            this.$notify({
              title: this.$i18n.t('common.tip'),
              message: i18n.t('msg.DELET_SUCCESS'),
              type: 'success',
              duration: 2000
            })
            this.list.splice(index, 1)
            this.getList()
          })
        })
        .catch(err => { console.error(err) })
    },
    // 过滤相关信息
    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    }
  }
}
</script>
<style>

.sortable-ghost {
  opacity: 0.9;
  color: #fff !important;
  background: #b143e0 !important;
}

</style>
<style lang="scss" scoped>
.dashboard-editor-container {
  padding: 32px;
  height: 800px;
  background-color: white;
  position: relative;

  .github-corner {
    position: absolute;
    top: 0px;
    border: 0;
    right: 0;
  }

  .chart-wrapper {
    background: #fff;
    padding: 16px 16px x0;
    //margin-bottom: 32px;
  }
}

@media (max-width:1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
